package util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author Karl
 * @Date 2023/1/10 - 21:07
 */
public class MyDateUtil {

    private MyDateUtil() {
    }

    private static final ThreadLocal<DateFormat> THREAD_LOCAL = ThreadLocal.withInitial(
            () -> new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US)
    );

    public static Date parseGMTStr(String str) {
        Date date = null;
        try {
            date = THREAD_LOCAL.get().parse(str);
        } catch (ParseException e) {
            MyUtil.log("exception : %s %s", e.getClass(), e.getLocalizedMessage());
        }
        return date;
    }

    /**
     * 返回一个当前代理服务器调用这个方法时间加上 off 秒的格林尼治时间字符串
     *
     * @param off 加上的时间 单位为秒
     * @return
     */
    public static String formatGMTStr(int off) {

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, off);
        return THREAD_LOCAL.get().format(cal.getTime());
    }

    /**
     * 返回两个格林尼治时间的时间差，str1-str2
     * @param str1 HTTP格林尼治时间字符串
     * @param str2 HTTP格林尼治时间字符串
     * @return str1-str2的毫秒时间差
     * @throws ParseException 字符串不是HTTP格林尼治时间格式时抛异常
     */
    public static long calGapMillTime(String str1, String str2) throws ParseException {
        DateFormat format = THREAD_LOCAL.get();
        Date date = format.parse(str1);
        Date date2 = format.parse(str2);
        return date.getTime() - date2.getTime();
    }

    /**
     * 返回格林尼治时间和当前服务器时间差，当前服务器时间-str
     * @param str1 HTTP格林尼治时间字符串
     * @return 当前服务器时间-str，单位毫秒
     * @throws ParseException
     */
    public static long calGapMillTime(String str1) throws ParseException {
        DateFormat format = THREAD_LOCAL.get();
        Calendar cal = Calendar.getInstance();
        Date date = format.parse(str1);
        return cal.getTime().getTime()- date.getTime();
    }

    public static String getNowGMTTime(){
        Calendar cal = Calendar.getInstance();
        return THREAD_LOCAL.get().format(cal.getTime());
    }
}
